package com.iphone.extra.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.iphone.extra.R;

public class RoundImageView extends ImageView {


    private Bitmap mBitmap;

    private final int RATIO;
    private final Paint mPaint;

    public RoundImageView(Context context) {
        this(context, null, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
        mPaint.setAntiAlias(true);
        RATIO = getResources().getDimensionPixelOffset(R.dimen.widget_bg_round_ratio);
    }

    public void setBitmap(Bitmap bitmap) {
        mBitmap = bitmap;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBitmap != null) {
            Bitmap bitmap = createRound(mBitmap);
            canvas.drawBitmap(bitmap, 0, 0, mPaint);
        }
    }

    private Bitmap createRound(Bitmap bitmap) {
        final int w = getWidth();
        final int h = getHeight();
        if (w > 0 && h > 0) {
            Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, w, h);
            final RectF rectF = new RectF(rect);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            canvas.drawARGB(0, 0, 0, 0);
            canvas.drawRoundRect(rectF, RATIO, RATIO, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        }
        return bitmap;
    }
}
